package com.spring.demo.controller;

import java.security.Principal;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.hibernate.HibernateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.spring.demo.domain.User;
import com.spring.demo.page.PageCondition;
import com.spring.demo.service.UserService;

@Controller
public class UserController extends BaseController {
	
	private static final Logger LOG = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	private UserService userService;

	@RequestMapping(value = "/users/register", method = RequestMethod.GET)
	public String register(Model model) {
		System.out.println("------------- register ------------");
		model.addAttribute(new User());
		return "register";
	}
	
	@RequestMapping(value = "/users/register", method = RequestMethod.POST)
	public String persistUser(@Valid User user, BindingResult result, HttpServletRequest request)
			throws HibernateException, SQLException {
		System.out.println("------------- persistUser ------------");
		LOG.info(user.getUserName());
		LOG.info(user.getLoginName());
		LOG.info(user.getPassword());
		
		userService.save(user);
		return "redirect:../user/search";
	}
	
	@RequestMapping(value = "/user/search", method = RequestMethod.GET)
	public void search(PageCondition pageCondition, Principal currentUser, Model model) {
		if (pageCondition == null) {
			pageCondition = new PageCondition();
			pageCondition.setPage(0);
			pageCondition.setSize(1);
		}
		Page<User> users = userService.findAll(pageCondition);
		pageCondition.setTotalPage(users.getTotalPages());
		model.addAttribute(users.getContent());
	}
	
	@RequestMapping(value = "/user/list", method = RequestMethod.GET)
	public String list(PageCondition pageCondition, Principal currentUser, Model model) {
		if (pageCondition == null) {
			pageCondition = new PageCondition();
			pageCondition.setPage(0);
			pageCondition.setSize(1);
		}
		Page<User> users = userService.findAll(pageCondition);
		pageCondition.setTotalPage(users.getTotalPages());
		model.addAttribute(users.getContent());
		return "user/search";
	}
	
	@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
	public String deleteUser(@PathVariable Long id) {
		userService.deleteUser(id);
		return "redirect:../user/search";
	}
	
}
